# -*- coding: UTF-8 -*-
from pyLib.databaseManage import ACCOUNT_DATABASE
from tools.Initialization import USER_PWD, USER_USER
from application.user_account_api import UserAccount


class USER:

    @staticmethod
    def login(user=USER_USER, pwd=USER_PWD, get_cookies=False):
        r = UserAccount().login({"username": user, "password": pwd})
        data = r.json().get("data")
        if r.json().get('status'):
            if get_cookies:
                cookie = ''
                for name, value in r.cookies.items():
                    cookie += '{0}={1};'.format(name, value)
                return data.get("token"), data.get("userId"), cookie
            else:
                return data.get("token"), data.get("userId")
        else:
            print(r.json().get('message'))

    @staticmethod
    def get_headers(user=USER_USER, pwd=USER_PWD, enterprise_code=None):
        """账户中心获取用户的通用请求头"""
        r = UserAccount().login({"username": user, "password": pwd})
        cookie = ''
        for name, value in r.cookies.items():
            cookie += '{0}={1};'.format(name, value)
        token = r.json().get("data").get("token")
        userId = r.json().get("data").get("userId")
        header = {"cookie": cookie, "token": token, "user": userId, "language": "zh-cn"}
        # 查询企业id(传code就根据code查id，否则查默认的企业id)
        if enterprise_code:
            sql = f"SELECT id FROM `enterprise_info` WHERE enterprise_code='{enterprise_code}'"
        else:
            sql = f"SELECT enterprise_id FROM `user_enterprise_pk` where default_enterprise=1 AND user_id='{userId}'"
        try:
            enterprise_id = ACCOUNT_DATABASE.execute_sql(sql)[0][0]
            header["enterprise-id"] = enterprise_id
        except:
            pass
        return header
    #
    # @staticmethod
    # def get_s_header(userId):
    #     """
    #     获取账户中心的对外接口请求头
    #     :param userId: 用户id
    #     :return: 对外接口请求头
    #     """
    #     platform_code, platform_secret = ACCOUNT_DATABASE.execute_sql(
    #         f"SELECT platform_code,platform_secret FROM `authorization_info`")[0]
    #     # 生成13位时间戳
    #     t = str(round(time.time() * 1000))
    #     sign = get_md5(t + "&@&" + userId + "&@&" + platform_code + "&@&" + platform_secret)
    #     header = {"platform-code": platform_code,
    #               "platform-secret": platform_secret,
    #               "sign": sign,
    #               "timestamp": t,
    #               "user": userId}
    #     return header


if __name__ == '__main__':
    print(USER.login("admin", "Abc@1234"))
